/*
 * 时间：2018-9-26
 * 功能：简易聊天界面
 */
package com.example.zht.chatapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    // 所有消息列表
    private List<Msg> msgList = new ArrayList<Msg>();
    // 内容输入框
    private EditText inputText;
    // 发送消息按钮
    private Button send;

    private RecyclerView msgRecyclerView;
    // RecyclerView 的适配器
    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMsgs(); // 初始化消息数据
        inputText = findViewById(R.id.input_text);
        send = findViewById(R.id.send);
        msgRecyclerView = findViewById(R.id.msg_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        send.setOnClickListener(v -> {
            String content = inputText.getText().toString();
            if (!"".equals(content.trim())) {
                Msg msg = new Msg(content, Msg.TYPE_SENT);
                msgList.add(msg);
                adapter.notifyItemInserted(msgList.size() - 1); // 当有新消息时，刷新ListView中的显示
                msgRecyclerView.scrollToPosition(msgList.size() - 1); // 将ListView定位到最后一行
                inputText.setText(""); // 清空输入框中的内容
            } else {
                Toast.makeText(this, "不能发送空消息！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initMsgs() {
        Msg msg1 = new Msg("你好！美女", Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("你好！你是谁？", Msg.TYPE_SENT);
        msgList.add(msg2);
        Msg msg3 = new Msg("我是 ZHT，很高兴见到你！", Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}
